package top.wettis.chat.constant.exception;

import cn.dev33.satoken.exception.*;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.wettis.chat.pojo.VO.Result;

@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Log logger = LogFactory.get();

    //TODO 上线时删除 System.out.println()

    // 拦截：未登录异常
    @ExceptionHandler(NotLoginException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Exception> handlerException(NotLoginException e) {
        logger.error(e.getMessage(),e);
        e.printStackTrace();
        return Result.errorMsg("未登录");
    }

    // 拦截：缺少权限异常
    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Exception> handlerException(NotPermissionException e) {
        logger.error(e.getMessage(),e);
        return Result.errorMsg("缺少权限");
    }

    // 拦截：缺少角色异常
    @ExceptionHandler(NotRoleException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Exception> handlerException(NotRoleException e) {
        logger.error(e.getMessage(),e);
        return Result.errorMsg("缺少角色");
    }

    // 拦截：二级认证校验失败异常
    @ExceptionHandler(NotSafeException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Exception> handlerException(NotSafeException e) {
        logger.error(e.getMessage(),e);
        return Result.errorMsg("校验失败");
    }

    // 拦截：服务封禁异常
    @ExceptionHandler(DisableServiceException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Exception> handlerException(DisableServiceException e) {
        logger.error(e.getMessage(),e);
        System.out.println("当前账号 " + e.getService() + " 服务已被封禁 (level=" + e.getLevel() + ")：" + e.getDisableTime() + "秒后解封");
        return Result.errorMsg("当前账号封禁中，如有疑问请联系客服");
    }

    // 拦截：Http Basic 校验失败异常
    @ExceptionHandler(NotBasicAuthException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public Result<Exception> handlerException(NotBasicAuthException e) {
        logger.error(e.getMessage(),e);
        return Result.errorMsg("no basic auth");
    }

    // 拦截：参数校验错误
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    public Result<Exception> handlerException(MethodArgumentNotValidException e){
        return Result.errorMsg(e.getMessage());
    }

    // 未知错误拦截
    @ExceptionHandler(Exception.class)
    public Result<Exception> handlerException(Exception e) {
        logger.error(e.getMessage(),e);
        return Result.errorMsg("未知错误");
    }
}
